package com.niuwa.p2p.action.redenvelope;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.entity.redenvelope.RedEnvelope;
import com.niuwa.p2p.service.redenvelope.IRedEnvelopeService;

/**
 * 
 * @ClassName: UserAction
 * @Descriptio 用户Action
 * @author: jishengjun
 * 
 */

public class redEnvelopeManageAction extends JsonAction {

	private static final long serialVersionUID = -8900124777631535966L;

	/** 日志 */
	private static Logger logger = Logger
			.getLogger(redEnvelopeManageAction.class);

	@Autowired
	private IRedEnvelopeService redEnvelopeService;

	// 文件
	private File uploadExcel;
	// 文件名
	private String uploadExcelFileName;

	/*
	 * 
	 * 跳转到红包管理列表页面
	 * 
	 * @return String
	 */
	@Action(value = "redEnvelopeList", results = { @Result(location = "redEnvelopeList.jsp", name = SUCCESS) })
	public String gotoRedEnvelopeListPage() {
		return SUCCESS;
	}

	/*
	 * 
	 * 跳转到红包审核列表页面
	 * 
	 * @return String
	 */
	@Action(value = "redEnvelopeSendAuditing", results = { @Result(location = "redEnvelopeSendAuditingList.jsp", name = SUCCESS) })
	public String gotoredEnvelopeSendAuditingListPage() {
		return SUCCESS;
	}

	/*
	 * 
	 * 跳转到手动发放红包页面
	 * 
	 * @return String
	 */
	@Action(value = "handSendRedEnvelope", results = { @Result(location = "handSendRedEnvelopeList.jsp", name = SUCCESS) })
	public String gotoredhandSendRedEnvelopeListPage() {
		return SUCCESS;
	}

	/**
	 * 查询红包列表或红包发放审核列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "searchRedEnvelopeList")
	public String searchRedEnvelopeList() throws Exception {
		setObjectReSult(queryPage());
		logger.info("searchRedEnvelopeList action execute success");
		return NONE;
	}

	/**
	 * 分页查询
	 * 
	 * @return Pagination<NwAccount>
	 */
	private PageBean<RedEnvelope> queryPage() {

		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();

		// 查选分页集合
		PageBean<RedEnvelope> page = redEnvelopeService
				.searchRedEnvelopeList(paramMap);

		return page;
	}

	/**
	 * 查询红包发放审核列表不分页
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "searchAllRedEnvelopeList")
	public String searchAllRedEnvelopeList() throws Exception {
		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();
		List<RedEnvelope> redEnvelopeList = redEnvelopeService
				.searchAllRedEnvelopeList(paramMap);
		setObjectReSult(redEnvelopeList);
		logger.info("searchAllRedEnvelopeList action execute success");
		return NONE;
	}

	/**
	 * 一键通过或一键拒绝
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "allPassOrAllReject")
	public String allPassOrAllReject() throws Exception {
		String message = new String();
		JsonResult results = new JsonResult();
		HttpServletRequest request = ServletActionContext.getRequest();
		String redEnvelopeStatus = request.getParameter("redEnvelopeStatus");
		String jsonArr = request.getParameter("jsonArr");
		@SuppressWarnings("unchecked")
		List<JSONObject> jsonList = (List<JSONObject>) JSONArray
				.fromObject(jsonArr);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("redEnvelopeStatus", redEnvelopeStatus);
		paramMap.put("jsonList", jsonList);
		try {
			redEnvelopeService.updateRedEnvelope(paramMap);
			if("ALLREADY_AUDIT".equals(redEnvelopeStatus)){
				message = "全部审核通过成功";
			}else{
				message = "全部审核拒绝成功";
			}
			logger.info("allPassOrAllReject action execute success");

		} catch (Exception e) {
			message = "操作失败";
			e.printStackTrace();
		}
		results.setMsg(message);
		setResult(results);
		return NONE;
	}

	/**
	 * 红包批量插入
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "redEnvelopeBatchInsert")
	public String redEnvelopeBatchInsert() throws Exception {
		String message = new String();
		JsonResult results = new JsonResult();
		HttpServletRequest request = ServletActionContext.getRequest();
		String jsonArr = request.getParameter("jsonArr");
		@SuppressWarnings("unchecked")
		List<JSONObject> jsonList = (List<JSONObject>) JSONArray
				.fromObject(jsonArr);
		try {
			redEnvelopeService.insertRedEnvelopeBatch(jsonList);
			message = "新增成功";
			logger.info("redEnvelopeBatchInsert action execute success");

		} catch (Exception e) {
			message = "新增失败";
			e.printStackTrace();
		}
		results.setMsg(message);
		setResult(results);
		return NONE;
	}

	/**
	 * 红包批量插入
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "uploadRedEnvelope")
	public String uploadRedEnvelope() {
		String message = new String();
		List<String> availPlatformList = new ArrayList<String>();
		List<String> custNameList = searchAllCustName();
		List<Map<String, Object>> redEnvelopeList = new ArrayList<Map<String, Object>>();
		availPlatformList.add("全部");
		availPlatformList.add("WEB");
		availPlatformList.add("APP");
		JsonResult results = new JsonResult();
		try {
			FileInputStream input = new FileInputStream(uploadExcel);
			Workbook wb = null;
			// 根据文件格式(2003或者2007)来初始化
			if (uploadExcelFileName.endsWith("xlsx")) {
				wb = new XSSFWorkbook(input);
			} else {
				
				wb = new HSSFWorkbook(input);
			}

			Sheet sheet = wb.getSheetAt(0);
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			int totalRow = sheet.getLastRowNum();
			if (totalRow < 0) {
				message = "导入的红包模板不能为空";
				throw new RuntimeException("导入的红包模板不能为空");
			}
			Row headRow = sheet.getRow(0);
			/*for (int i = 0; i < 8; i++) {
				String headValue = headRow.getCell(i).getStringCellValue();
				if (headValue == null) {
					message = "导入的红包模板不能为空";
					throw new RuntimeException("导入的红包模板不能为空");
				}
			}*/
			String name = new String();
			String amount = new String();
			String custName = new String();
			String availPlatform = new String();
			String startDate = new String();
			String endDate = new String();
			String availActions = new String();
			String consumedPercent =new String();
			
			try {
				 name = headRow.getCell(0).getStringCellValue().trim();
			     amount = headRow.getCell(1).getStringCellValue().trim();
				 custName = headRow.getCell(2).getStringCellValue().trim();
				 availPlatform = headRow.getCell(3).getStringCellValue().trim();
				 startDate = headRow.getCell(4).getStringCellValue().trim();
				 endDate = headRow.getCell(5).getStringCellValue().trim();
				 availActions = headRow.getCell(6).getStringCellValue().trim();
				consumedPercent = headRow.getCell(7).getStringCellValue().trim();
				
			} catch (Exception e1) {
				message = "标题头输入格式不正确,请修改";
				e1.printStackTrace();
				throw new RuntimeException();

			}

			if (!"红包名称".equals(name)) {
				message = "1行1列,红包名称不正确";
				throw new RuntimeException("1行1列,红包名称不正确");
			}
			if (!"金额(元)".equals(amount)) {
				message = "1行2列,金额(元)不正确";
				throw new RuntimeException("1行2列,金额(元)不正确");
			}
			if (!"发放用户".equals(custName)) {
				message = "1行3列,发放用户不正确";
				throw new RuntimeException("1行3列,发放用户不正确");
			}
			if (!"适用产品".equals(availPlatform)) {
				message = "1行4列,适用产品不正确";
				throw new RuntimeException("1行4列,适用产品不正确");
			}
			if (!"生效日期".equals(startDate)) {
				message = "1行5列,生效日期不正确";
				throw new RuntimeException("1行5列,生效日期不正确");
			}
			if (!"失效日期".equals(endDate)) {
				message = "1行6列,失效日期不正确";
				throw new RuntimeException("1行6列,失效日期不正确");
			}
			if (!"使用范围".equals(availActions)) {
				message = "1行7列,使用范围不正确";
				throw new RuntimeException("1行7列,使用范围不正确");
			}
			if (!"使用比例(%)".equals(consumedPercent)) {
				message = "1行8列,使用比例不正确";
				throw new RuntimeException("1行8列,使用比例不正确");
			}
			for (int i = 1; i <= totalRow; i++) {
				Row row = sheet.getRow(i);
				String name1 = new String();
			    String amount1 =new String();
				String custName1 = new String();
				String availPlatform1 = new String();
				String startDate1 = new String();
				String endDate1 = new String();
				String availActions1 = new String();
				String consumedPercent1 =new String();
				try {
					row.getCell(0).setCellType(HSSFCell.CELL_TYPE_STRING);
					name1 = row.getCell(0).getStringCellValue();
				} catch (Exception e1) {
					message = (i + 1) + "行1列,红包名称输入格式不正确,请修改";
					e1.printStackTrace();
					throw new RuntimeException();

				}
				if (StringUtil.isNullOrEmpty(name1)) {
					message = (i + 1) + "行1列,红包名称输入不能为空,请修改";
					throw new RuntimeException();
				}
				if (name1.length() > 20) {
					message = (i + 1) + "行1列,红包名称输入超出限定长度,请修改";
					throw new RuntimeException();
				}
				try {
				row.getCell(1).setCellType(HSSFCell.CELL_TYPE_STRING);
				amount1 =row.getCell(1).getStringCellValue();
				} catch (Exception e1) {
					message = (i + 1) + "行2列,金额输入格式不正确,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}

				if (amount1 == null||"".equals(amount1)) {
					message = (i + 1) + "行2列,金额不能为空,请修改";
					throw new RuntimeException();
				}
				if (!StringUtil.isLong(amount1.toString())) {
					message = (i + 1) + "行2列,金额输入错误,请修改";
					throw new RuntimeException();
				}
				if (amount1.toString().length() > 10) {
					message = (i + 1) + "行2列,金额输入超出限定长度,请修改";
					throw new RuntimeException();
				}
				try {
					row.getCell(2).setCellType(HSSFCell.CELL_TYPE_STRING);
					custName1 = row.getCell(2).getStringCellValue().trim();
				} catch (Exception e1) {
					if(!"".equals(custName1)){
						message = (i + 1) + "行3列,发放用户输入格式不正确,请修改";
						e1.printStackTrace();
						throw new RuntimeException();
					}
					
				}

				if (!StringUtil.isNullOrEmpty(custName1)) {
					if (custName1.length() > 20) {
						message = (i + 1) + "行3列,发放用户输入超出限定长度,请修改";
						throw new RuntimeException();
					}
					if (!custNameList.contains(custName1)) {
						message = (i + 1) + "行3列,发放用户不存在,请修改";
						throw new RuntimeException();

					}
				}
			
				try {
					row.getCell(3).setCellType(HSSFCell.CELL_TYPE_STRING);
					availPlatform1 = row.getCell(3).getStringCellValue().trim();
				} catch (Exception e1) {
					message = (i + 1) + "行4列,适用产品输入格式不正确,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}
				if (StringUtil.isNullOrEmpty(availPlatform1)) {
					message = (i + 1) + "行4列,适用产品不能为空,请修改";
					throw new RuntimeException();
				}
				if (availPlatform1.length() > 20) {
					message = (i + 1) + "行4列,适用产品输入超出限定长度,请修改";
					throw new RuntimeException();
				}

				if (!availPlatformList.contains(availPlatform1)) {
					message = (i + 1) + "行4列,适用产品只能为'全部','WEB','APP',请修改";
					throw new RuntimeException();
				}

				Date startDate2;
				try {
					startDate2 = row.getCell(4).getDateCellValue();
					startDate1 = sdf.format(startDate2);
				} catch (Exception e1) {
					message = (i + 1) + "行5列,生效日期错误,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}

				if (StringUtil.isNullOrEmpty(startDate1)) {
					message = (i + 1) + "行5列,生效日期不能为空,请修改";
					throw new RuntimeException();
				}
				/*
				 * try { Date newStartDate=new Date(startDate1);
				 * startDate1=sdf.format(newStartDate); } catch (Exception e) {
				 * message=(i+1)+"行5列,生效日期错误,请修改"; e.printStackTrace(); throw
				 * new RuntimeException(); }
				 */
				Date endDate2;
				try {
					endDate2 = row.getCell(5).getDateCellValue();
					endDate1 = sdf.format(endDate2);
				} catch (Exception e1) {
					message = (i + 1) + "行6列,失效日期错误,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}
				if (StringUtil.isNullOrEmpty(endDate1)) {
					message = (i + 1) + "行6列,失效日期不能为空,请修改";
					throw new RuntimeException();
				}

				if (sdf.parse(endDate1).getTime() < sdf.parse(startDate1)
						.getTime()) {
					message = (i + 1) + "行,失效日期不能小于生效日期,请修改";
					throw new RuntimeException();
				}

				try {
					row.getCell(6).setCellType(HSSFCell.CELL_TYPE_STRING);
					availActions1 = row.getCell(6).getStringCellValue().trim();
				} catch (Exception e1) {
					message = (i + 1) + "行7列,使用范围输入格式不正确,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}

				if (StringUtil.isNullOrEmpty(availActions1)) {
					message = (i + 1) + "行7列,使用范围不能为空,请修改";
					throw new RuntimeException();
				}
				String[] availActionsArr = availActions1.split(",");
				List<String> availActionsList =new ArrayList<String>();
				 availActionsList.add("直投");
				 availActionsList.add("计划");
				 availActionsList.add("债转");
				 availActionsList.add("借抵");
				 availActionsList.add("兑现");
				for (int k = 0; k < availActionsArr.length; k++) {
					if ( !availActionsList.contains(availActionsArr[k])) {
						message = (i + 1) + "行,7列使用范围错误,请修改";
						throw new RuntimeException();
					}
				}
               String availActionsStr="直投,计划,债转,借抵,兑现";
				String[] availActionsStrAttr = availActionsStr.split(",");
				for (int n = 0; n < availActionsStrAttr.length; n++) {
					int start = availActions1.indexOf(availActionsStrAttr[n]);
					int second = availActions1.indexOf(availActionsStrAttr[n],
							start + 1);
					if (second >= 0) {
						message = (i + 1) + "行,7列使用范围使用范围内容不能重复,请修改";
						throw new RuntimeException();
					}
				}
				try {
					row.getCell(7).setCellType( HSSFCell.CELL_TYPE_STRING);
					consumedPercent1 = row.getCell(7).getStringCellValue();
				} catch (Exception e1) {
					message = (i + 1) + "行8列,使用比例输入格式不正确,请修改";
					e1.printStackTrace();
					throw new RuntimeException();
				}
				if (StringUtil.isNullOrEmpty(consumedPercent1)) {
					message = (i + 1) + "行8列,使用比例不能为空,请修改";
					throw new RuntimeException();
				}
				if (consumedPercent1.length() > 10) {
					message = (i + 1) + "行8列,使用比例输入超出限定长度,请修改";
					throw new RuntimeException();
				}
				if (!StringUtil.isInt(consumedPercent1.toString())) {
					message = (i + 1) + "行8列,使用比例输入错误,请修改";
					throw new RuntimeException();
				}
				if (Integer.parseInt(consumedPercent1) > 100
						|| Integer.parseInt(consumedPercent1.toString()) < 0) {
					message = (i + 1) + "行8列,使用比例范围为0-100,请修改";
					throw new RuntimeException();
				}
				Map<String, Object> redEnvelopeMap = new HashMap<String, Object>();
				redEnvelopeMap.put("name", name1);
				redEnvelopeMap.put("amount", amount1);
				redEnvelopeMap.put("custName", custName1);
				redEnvelopeMap.put("availPlatform", availPlatform1);
				redEnvelopeMap.put("startDate", startDate1);
				redEnvelopeMap.put("endDate", endDate1);
				redEnvelopeMap.put("availActions",availActions1);
				redEnvelopeMap.put("consumedPercent", consumedPercent1);
				redEnvelopeList.add(redEnvelopeMap);
			}
			message = "红包导入成功";
			logger.info("redEnvelopeBatchInsert action execute success");

		} catch (Exception e) {
			redEnvelopeList.clear();
			if (StringUtil.isNullOrEmpty(message)) {
				message = "红包导入失败";
			}
			e.printStackTrace();
		}
		results.setMsg(message);
		results.setData(redEnvelopeList);
		setResult(results);
		return NONE;
	}

	/**
	 * 红包批量插入
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value ="searchAllCustName")
	public String searchAllCustName2() throws Exception {
		setObjectReSult(searchAllCustName());
		return NONE;
	}

	// 查询所有客户
	public List<String> searchAllCustName() {
		return redEnvelopeService.searchAllCustName();

	}

	/*
	 * //根据账户号查询明细
	 * 
	 * @Action(value="getNwAccountByAcctNo") public String
	 * getNwAccountByAcctNo(){ NwAccount =
	 * nwAccountManagerService.getNwAccountByAcctNo(NwAccount.getAcctNo());
	 * setObjectReSult(NwAccount); return NONE; }
	 */
	/**
	 * 
	 * 增加牛娃账户
	 *
	 */
	/*
	 * @Action(value="addNWAccount") public String addNWAccount(){ String
	 * message=new String(); JsonResult results=new JsonResult(); try {
	 * List<NwAccount>
	 * nwAccountList=nwAccountManagerService.getNwAccountByNo(NwAccount);
	 * if(nwAccountList.size()!=0){ message="账户名重复,新增失败"; throw new
	 * RuntimeException(); }else{
	 * nwAccountManagerService.addNWAccount(NwAccount); message="新增成功";
	 * results.setMsg(message); setResult(results); } } catch (Exception e) {
	 * if(!("账户名重复,新增失败".equalsIgnoreCase(message))){ message="新增失败"; }
	 * results.setMsg(message); setResult(results); e.printStackTrace(); }
	 * return NONE;
	 * 
	 * }
	 */

	/**
	 * 
	 * 修改牛娃账户
	 *
	 */
	/*
	 * @Action(value="updateNwAccountByAcctNo") public String
	 * updateNwAccountByAcctNo(){ String message=new String(); JsonResult
	 * results=new JsonResult(); try { List<NwAccount>
	 * nwAccountList=nwAccountManagerService.getNwAccountByNo(NwAccount);
	 * if(nwAccountList.size()==0){ message="账户不存在,修改失败"; throw new
	 * RuntimeException(); }else{
	 * nwAccountManagerService.updateNwAccountByAcctNo(NwAccount);
	 * message="修改成功"; results.setMsg(message); setResult(results); } } catch
	 * (Exception e) { if(!("账户不存在,修改失败".equalsIgnoreCase(message))){
	 * message="修改失败"; } results.setMsg(message); setResult(results);
	 * e.printStackTrace(); } return NONE;
	 * 
	 * }
	 */

	public IRedEnvelopeService getRedEnvelopeService() {
		return redEnvelopeService;
	}

	public void setRedEnvelopeService(IRedEnvelopeService redEnvelopeService) {
		this.redEnvelopeService = redEnvelopeService;
	}

	public File getUploadExcel() {
		return uploadExcel;
	}

	public void setUploadExcel(File uploadExcel) {
		this.uploadExcel = uploadExcel;
	}

	public String getUploadExcelFileName() {
		return uploadExcelFileName;
	}

	public void setUploadExcelFileName(String uploadExcelFileName) {
		this.uploadExcelFileName = uploadExcelFileName;
	}
	

}
